/*
 * Copyright 2016 Wealth Inc. All rights reserved.
 */
package com.wealth.order.service.impl;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collection;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.transaction.Transactional;

import org.apache.commons.lang3.RandomStringUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Row;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.domain.Sort.Direction;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Component;

import com.wealth.bank.entity.Picked;
import com.wealth.cart.entity.Cart;
import com.wealth.cart.entity.CartItem;
import com.wealth.cart.enums.CartStatusEnum;
import com.wealth.cart.repository.CartDao;
import com.wealth.cart.repository.CartItemDao;
import com.wealth.cart.service.ICartItemService;
import com.wealth.cart.service.ICartService;
import com.wealth.commodity.entity.Goods;
import com.wealth.commodity.entity.GoodsVirtual;
import com.wealth.commodity.enums.GoodsStatusEnum;
import com.wealth.commodity.repository.GoodsDao;
import com.wealth.commodity.service.IGoodsService;
import com.wealth.commodity.service.IPurrestrictionsService;
import com.wealth.coupon.entity.CouponRecord;
import com.wealth.coupon.enums.CouponRecordStatusEnum;
import com.wealth.coupon.repository.CouponRecordDao;
import com.wealth.coupon.util.LabelFileEncrypt;
import com.wealth.lottery.service.ILotteryActivityService;
import com.wealth.lottery.service.ILotteryNumberService;
import com.wealth.member.entity.Address;
import com.wealth.member.entity.Member;
import com.wealth.member.entity.Membership;
import com.wealth.member.service.IAddressService;
import com.wealth.member.service.IMembershipService;
import com.wealth.merchant.entity.Activity;
import com.wealth.merchant.entity.Merchant;
import com.wealth.merchant.enums.MarketEnum;
import com.wealth.merchant.repository.ActivityDao;
import com.wealth.merchant.service.IMerchantService;
import com.wealth.order.entity.Order;
import com.wealth.order.entity.OrderItem;
import com.wealth.order.entity.OrderPlat;
import com.wealth.order.entity.OrderVirtual;
import com.wealth.order.enums.OrderStatusEnum;
import com.wealth.order.enums.PayStatusEnum;
import com.wealth.order.enums.SignStatusEnum;
import com.wealth.order.repository.OrderDao;
import com.wealth.order.repository.OrderItemDao;
import com.wealth.order.repository.OrderPlatDao;
import com.wealth.order.service.IOrderPlatService;
import com.wealth.order.service.IOrderService;
import com.wealth.order.service.IOrderVirtualService;
import com.wealth.order.service.IVoucherRecordService;
import com.wealth.order.vo.GoodsVO;
import com.wealth.order.vo.MerchantVO;
import com.wealth.order.vo.OrderVO;
import com.wealth.payment.enums.PaymentTypeEnum;
import com.wealth.platform.entity.Account;
import com.wealth.platform.entity.MerchantRate;
import com.wealth.platform.repository.PlatformActivityDao;
import com.wealth.platform.service.IAccountService;
import com.wealth.platform.service.IMerchantRateService;
import com.wealth.sms.enums.MessageTemplateEnum;
import com.wealth.sms.service.IMessageChannelService;
import com.wealth.system.entity.Corporation;

import iaas.enums.StatusEnum;
import iaas.enums.YesOrNoEnum;
import iaas.persistence.DynamicSpecifications;
import iaas.persistence.SearchFilter;
import iaas.persistence.SearchFilter.Operator;
import iaas.service.impl.BaseServiceImpl;
import iaas.utils.CommonUtil;
import iaas.utils.Reflections;
import iaas.utils.ResultObject;
import iaas.web.JqGridRequest;

/**
 * @author chan
 * @version 1.0
 * @since 1.0
 */

@Component
public class OrderPlatServiceImpl extends BaseServiceImpl<OrderPlat> implements
		IOrderPlatService {

	@Autowired
	private OrderDao orderDao;
	@Autowired
	private OrderItemDao orderItemDao;
	@Autowired
	private OrderPlatDao orderPlatDao;
	@Autowired
	private CartItemDao cartItemDao;
	@Autowired
	private GoodsDao goodsDao;
	@Autowired
	private CartDao cartDao;
	@Autowired
	private ActivityDao activityDao;
	@Autowired
	private PlatformActivityDao platformActivityDao;
	@Autowired
	private ICartService cartService;
	@Autowired
	private IOrderService orderService;
	@Autowired
	private IGoodsService goodsService;
	@Autowired
	private IAddressService addressService;
	@Autowired
	private IMessageChannelService messageChannelService;
	@Autowired
	private ICartItemService cartItemService;
	@Autowired
	IMembershipService iMembershipService;
	@Autowired
	private IMerchantRateService merchantRateService;
	@Autowired
	private IAccountService iAccountService;
	@Autowired
	private CouponRecordDao couponRecordDao;
	@Autowired
	private ILotteryActivityService lotteryActivityService;
	@Autowired
	private ILotteryNumberService lotteryNumberService;
	@Autowired
	private IOrderVirtualService orderVirtualService;
	@Autowired
	private IVoucherRecordService recordService;
	@Autowired
	private IMerchantService merchantService;
	@Autowired
	private IPurrestrictionsService purrestrictionsService;

	// 分页查询
	@Override
	public Page<OrderPlat> getOrderPlat(Long corpid, JqGridRequest request,
			Class<OrderPlat> clz) throws Exception {

		// 创建分页请求.
		int pageNumber = request.getPage();
		int pageSize = request.getRows();
		String sortType = StringUtils.isEmpty(request.getSidx()) ? "id"
				: request.getSidx();
		String sortDirection = StringUtils.isEmpty(request.getSord()) ? "desc"
				: request.getSord();
		Direction direction = sortDirection.equals("desc") ? Direction.DESC
				: Direction.ASC;
		Sort sort = new Sort(direction, sortType);
		PageRequest pageRequest = new PageRequest(pageNumber - 1, pageSize,
				sort);

		// 创建动态查询条件组合.
		Collection<SearchFilter> filters = SearchFilter.parse(request);
		// 过滤:企业
		if (Reflections.existsField("corp", clz)) {
			if (corpid != 1L) {
				filters.add(new SearchFilter("corp.id", Operator.EQ, corpid));
			}
		}

		Specification<OrderPlat> spec = DynamicSpecifications.bySearchFilter(
				filters, clz);
		return orderPlatDao.findAll(spec, pageRequest);
	}

	/** ---------------- 微信端 ---------------- */

	/** 保存银行订单 */
	@Transactional
	@Override
	/** 保存银行订单 */
	public ResultObject saveOrder(Long corpid, Long memberid, Long marketid,
			Long addressid, Long couponRecordId, Integer paymode,Long pickedId)
			throws Exception {

		double totalPrice = 0;// 该订单总价格
		MerchantRate merchantRate = merchantRateService
				.findMerchantRateByCorpId(corpid);// 积分转化率
		// TODO 补充by邢凡
		// 获取购物车
		Cart cart = cartDao.findCartByMemberIdAndMarketId(memberid, marketid);
		
		OrderVO ordervo = getVoBeforeSaveOrder(paymode, addressid,
				couponRecordId, marketid, memberid,cart);
		/* ------------ 判断库存 ------------ **/
		
		for (CartItem item : cart.getCartItems()) {
			if(item.getStatus()==CartStatusEnum.SELECT.getValue()){
				//是否启用库存
				if(item.getGoods().getIsInventory()==YesOrNoEnum.YES.getValue()){
					//能够减少库存
					if(item.getAmount()>item.getGoods().getRemain()){
						return new ResultObject("300", "商品库存不足", null);
					}
				}
				//商品限购处理
				if(item.getGoods().getIsPurRestrictions()!=null&&item.getGoods().getIsPurRestrictions()==YesOrNoEnum.YES.getValue()){
					//根据会员和商品ID查询限额数量
					int amount=purrestrictionsService.findByMemberIdAndGoodsId(memberid, item.getGoods().getId());
					//验证购买的商品是否超过限额
					boolean isPur=purrestrictionsService.checkPurRestrictions(item.getGoods(), item.getAmount()+amount);
					if(!isPur){
						return new ResultObject("300", item.getGoods().getName()+"商品每人限购"+item.getGoods().getPurRestrictionsNum()+"件", null);
					}
				}
				//判断商品是否下架
				if(item.getGoods().getStatus().intValue()==GoodsStatusEnum.DOWN.getValue()){
					return new ResultObject("300", item.getGoods().getName()+"已下架", null);
				}
			}
		}
		for (CartItem item : cart.getCartItems()) {
			if(item.getStatus()==CartStatusEnum.SELECT.getValue()){
				//是否启用库存
				if(item.getGoods().getIsInventory()==YesOrNoEnum.YES.getValue()){
					//减少商品库存
					item.getGoods().setRemain(item.getGoods().getRemain()-item.getAmount());
					goodsService.save(item.getGoods());
				}
			
			}
		}
		/** ------------ 业务逻辑 ------------ **/
		// 保存银行订单
		OrderPlat orderPlat = new OrderPlat();
		String orderno = String.valueOf(System.currentTimeMillis())
				+ RandomStringUtils.random(3, "1234567890");
		orderPlat.setOrderno(orderno);
		orderPlat.setCreateTime(new Date());
		orderPlat.setPaymode(paymode);
		orderPlat.setPaymentType(PaymentTypeEnum.WECHAT.getValue());
		orderPlat.setStatus(OrderStatusEnum.NOTPAY.getValue());
		orderPlat.setPaystatus(PayStatusEnum.NO.getValue());
		orderPlat.setActualPrice(ordervo.getActualPrice());
		orderPlat.setSubPrice(ordervo.getSubPrice());
		orderPlat.setTotal(ordervo.getTotal());
		orderPlat.setCorp(new Corporation(corpid));
		orderPlat.setMember(new Member(memberid));
		orderPlatDao.save(orderPlat);
		List<Order> orderList = new ArrayList<Order>();
		// 保存商户订单
		Address address=null;
		if(addressid!=null){
			 address = addressService.get(addressid);
		}
		for (MerchantVO vo : ordervo.getMerchantList()) {
			// 商户订单基础信息
			Order order = new Order();
			order.setCreateTime(new Date());
			order.setStatus(OrderStatusEnum.NOTPAY.getValue());
			order.setPaystatus(PayStatusEnum.NO.getValue());
			order.setDeliverstatus(YesOrNoEnum.NO.getValue());
			order.setSignstatus(SignStatusEnum.NO.getValue());
			order.setEvaluatestatus(YesOrNoEnum.NO.getValue());
			// 积分没有满减
			if (orderPlat.getPaymode() == 2) {
				order.setActualPrice(vo.getActualPrice());
				order.setSubPrice(0.0);
				order.setScore(vo.getScore());
				order.setTotal(vo.getActualPrice());
			} else {
				order.setActualPrice(vo.getActualPrice());
				order.setSubPrice(vo.getSubPrice());
				order.setTotal(vo.getTotal());
			}
			//自提商户
			Integer isPicked=vo.getMerchant().getIsPicked();
			if(isPicked==null || isPicked==0 ){
				order.setReceiver(address.getName());
				order.setTelephone(address.getTelephone());
				order.setAddress(address.getAddress()+" "+address.getStreet());
			}else {
				order.setPicked(new Picked(pickedId));
			}
			
			order.setOrderPlat(orderPlat);
			order.setMerchant(new Merchant(vo.getMerchantId()));
			order.setMember(orderPlat.getMember());
			order.setCorp(orderPlat.getCorp());

			// 商户订单明细
			List<OrderItem> itemList = new ArrayList<OrderItem>();
			int sum = 0;
			for (GoodsVO gvo : vo.getGoodsList()) {
				Goods goods = goodsDao.findOne(gvo.getGoodsid());
				OrderItem item = new OrderItem();
				item.setAmount(gvo.getAmount());
				item.setPrice(goods.getPrice());
				item.setGoods(goods);
				totalPrice += goods.getPrice();
				itemList.add(item);
				sum += gvo.getAmount();
			}
			order.setAmount(sum);
			order.setOrderItemList(itemList);
			

			ResultObject rs = orderService.saveOrder(order);
			if (!rs.getCode().equals("000")) {
				return rs;
			}
			Integer  idPicked=vo.getMerchant().getIsPicked();
			if(idPicked!=null && idPicked==1){//自提商户
				OrderVirtual orderVirtual=orderVirtualService.createOrderVirtual();
				order.setOrderVirtual(orderVirtual);
			}
			orderList.add(order);
		}

		orderPlat.setOrderList(orderList);

		// TODO
		// 判断支付类型，如果是积分城的话(检查积分)
		if (marketid == MarketEnum.SCORECITY.getValue()) {
			Membership membership = iMembershipService.get(memberid);// 会员信息
			if (membership != null && merchantRate != null) {
				if (membership.getAccount().getScore() >= (totalPrice * merchantRate
						.getScore())) {
					orderPlat.setTotal(totalPrice);
					orderPlat.setActualPrice(totalPrice);
					orderPlat.setSubPrice(0.0);
					orderPlat.setScore((int) totalPrice
							* merchantRate.getScore());
				} else {
					return new ResultObject("000", "积分不够", orderPlat.getId());
				}
			}
		}
		
		return new ResultObject("000", "保存银行订单成功", orderPlat.getId());
	}

	/** 支付银行订单 */
	@Transactional
	@Override
	public void payOrder(OrderPlat orderPlat) throws Exception {
          
		if (orderPlat.getPaystatus().intValue() == YesOrNoEnum.NO.getValue()) {
			// 银行订单 
			orderPlat.setPaystatus(PayStatusEnum.YES.getValue());
			orderPlat.setStatus(OrderStatusEnum.PAY.getValue());
			orderPlat.setPayTime(new Date());
			orderPlatDao.save(orderPlat);

			// 商户订单
			for (Order order : orderPlat.getOrderList()) {
				order.setStatus(OrderStatusEnum.PAY.getValue());
				orderService.payOrder(order);
				//
				Integer  idPicked=order.getMerchant().getIsPicked();
				if(idPicked!=null && idPicked==1){//自提商户
					recordService.saveVoucherRecord(order);
				}
			}
			
			
			// 修改购物车数据
			double carttotal = 0.0;
			int cartamount = 0;
			// 获取购物车
			Cart cart = cartDao.findCartByMemberIdAndMarketId(orderPlat.getMember().getId(), MarketEnum.BRAND.getValue());
			if(cart!=null){
				for (CartItem item : cart.getCartItems()) {
					if(item.getStatus()==CartStatusEnum.SELECT.getValue()){
						carttotal+=item.getAmount() * item.getGoods().getPrice();
						cartamount+=item.getAmount();
					}
				} 
				cart.setTotal(cart.getTotal() -carttotal);
				cart.setAmount(cart.getAmount() - cartamount);

				cartDao.save(cart);
				
				//删除购物车中下单成功的商品
				if(cart.getCartItems().size()>0){
					for (CartItem item : cart.getCartItems()) {
						if(item.getStatus()==CartStatusEnum.SELECT.getValue()){
							cartItemService.delete(item.getId());
						}
						
					}
				}
			}  
			// 减少积分
			// 如果orderPlat的paymode==2，减少积分
			// TODO
			if (orderPlat.getPaymode() == 2) {
				Account account = iAccountService
						.getAccountByMemberIdAndCorpId(orderPlat.getMember()
								.getId(), orderPlat.getCorp().getId());
				MerchantRate merchantRate = merchantRateService
						.findMerchantRateByCorpId(orderPlat.getCorp().getId());
				account.setScore((int) (account.getScore() - (orderPlat
						.getTotal() * merchantRate.getScore())));
				iAccountService.save(account);
			}
			
			//满足抽奖条件，增加一次抽奖次数
			lotteryActivityService.getByScoreGt(orderPlat.getTotal(),orderPlat.getCorp().getId(),orderPlat.getMember().getId());

			// 发送信息，增加记录
			Map<String, String> map = new HashMap<String, String>();
			map.put("orderno", orderPlat.getOrderno());
			messageChannelService.send(orderPlat.getCorp().getId(),
					MessageTemplateEnum.PAYSUCCESS.getValue(), orderPlat
							.getMember().getUsername(), map);
		}
	}

	/** 保存银行订单 - 惠生活 */
	public ResultObject saveOrderForHuiLife(Long corpid, Long memberid,
			Long goodsid, Integer amount, Long addressid, Integer paymode)
			throws Exception {

		Goods goods = goodsDao.findOne(goodsid);
		//Address address = addressService.get(addressid);
		
		//商品限购处理
		if(goods.getIsPurRestrictions()==YesOrNoEnum.YES.getValue()){
			//根据会员和商品ID查询限额数量
			int pAmount=purrestrictionsService.findByMemberIdAndGoodsId(memberid, goods.getId());
			//验证购买的商品是否超过限额
			boolean isPur=purrestrictionsService.checkPurRestrictions(goods, pAmount+amount);
			if(!isPur){
				return new ResultObject("300", goods.getName()+"商品每人限购"+goods.getPurRestrictionsNum()+"件", null);
			}
		}
		//判断商品是否下架
		if(goods.getStatus()==GoodsStatusEnum.DOWN.getValue()){
			return new ResultObject("300", goods.getName()+"已下架", null);
		}
		if(goods.getIsInventory()==YesOrNoEnum.YES.getValue()){
			//能够减少库存
			boolean flag = goodsService.decreaseRemain(goodsid,amount);
			if (!flag) {
				return new ResultObject("300", "商品库存不足", null);
			}
		}
		/** ------------ 业务逻辑 ------------ **/
		// 保存银行订单
		OrderPlat orderPlat = new OrderPlat();
		String orderno = String.valueOf(System.currentTimeMillis())
				+ RandomStringUtils.random(3, "1234567890");
		orderPlat.setOrderno(orderno);
		orderPlat.setCreateTime(new Date());
		orderPlat.setPaymode(paymode);
		orderPlat.setPaymentType(PaymentTypeEnum.WECHAT.getValue());
		orderPlat.setStatus(OrderStatusEnum.NOTPAY.getValue());
		orderPlat.setPaystatus(PayStatusEnum.NO.getValue());
		orderPlat.setActualPrice(goods.getPrice() * amount);
		orderPlat.setSubPrice(0d);
		orderPlat.setTotal(orderPlat.getActualPrice());
		orderPlat.setCorp(new Corporation(corpid)); // 银行
		orderPlat.setMember(new Member(memberid)); // 会员
		orderPlatDao.save(orderPlat);

		// 保存商户订单
		// 商户订单基础信息
		Order order = new Order();
		order.setCreateTime(new Date());
		order.setStatus(OrderStatusEnum.NOTPAY.getValue());
		order.setPaystatus(PayStatusEnum.NO.getValue());
		order.setSignstatus(SignStatusEnum.NO.getValue());
		order.setDeliverstatus(YesOrNoEnum.NO.getValue());
		order.setEvaluatestatus(YesOrNoEnum.NO.getValue());
		order.setActualPrice(orderPlat.getActualPrice());
		order.setSubPrice(orderPlat.getSubPrice());
		order.setTotal(orderPlat.getTotal());
		//order.setReceiver(address.getName()); // 收货信息
		//order.setTelephone(address.getTelephone());
		//order.setAddress(address.getAddress());
		order.setOrderPlat(orderPlat); // 银行订单
		order.setMerchant(goods.getMerchant()); // 商户
		order.setCorp(orderPlat.getCorp()); // 银行
		order.setMember(orderPlat.getMember()); // 会员

		// 商户订单明细
		List<OrderItem> itemList = new ArrayList<OrderItem>();
		OrderItem item = new OrderItem();
		item.setAmount(amount);
		item.setPrice(goods.getPrice());
		item.setGoods(goods);
		itemList.add(item);

		order.setAmount(amount);
		order.setOrderItemList(itemList);
		ResultObject rs = orderService.saveOrder(order);
		if (!rs.getCode().equals("000")) {
			return rs;
		}

		return new ResultObject("000", "保存银行订单成功", orderPlat.getId());

	}

	/** 保存订单前 获取购物车的数据 */
	@Override
	public OrderVO getVoBeforeSaveOrder(Integer paymode, Long addressId,
			Long couponRecordId, Long marketId, Long memberid,Cart cart) throws Exception {

		List<MerchantVO> merchantVOlists = new ArrayList<MerchantVO>();// 商户vo对象集合
		


		// 获取商户信息
		Map<String, Merchant> map = new HashMap<String, Merchant>();
		for (CartItem i : cart.getCartItems()) {
			map.put(i.getGoods().getMerchant().getId().toString(), i.getGoods()
					.getMerchant());
		}
		// 订单减免金额
		Double orderSubPrice = 0.0;
		// 遍历商户map集合
		for (String key : map.keySet()) {
			List<GoodsVO> goodsVOlists = new ArrayList<GoodsVO>(); // 商品vo对象集合
			MerchantVO merchantVO = new MerchantVO();// 商户vo对象
			boolean isMerchant = false;
			double total = 0.0;
			Merchant merchant = map.get(key);

			// 遍历购物车
			for (CartItem cartitem : cart.getCartItems()) {
				// 选中状态
				if (cartitem.getStatus() == CartStatusEnum.SELECT.getValue()) {
					// 当前商户
					if (cartitem.getMerchant().getId().equals(merchant
							.getId())) {

						total += cartitem.getAmount()
								* cartitem.getGoods().getPrice(); // 累计商户总金额

						// 商品vo
						GoodsVO goodsVO = new GoodsVO();// 商品vo对象
						goodsVO.setGoodsid(cartitem.getGoods().getId());
						goodsVO.setAmount(cartitem.getAmount());
						goodsVOlists.add(goodsVO);
						isMerchant = true;
						
					}

				}
			}
			if (isMerchant) {
				// 查询商户活动 计算是否满足商户的满减金额
				List<Activity> activities = activityDao
						.findByStatusAndMerchantId(
								StatusEnum.NORMAL.getValue(), merchant.getId());
				if (activities.size() > 0) {
					// 判断该商户下总金额是否满足商户的满减金额
					if (total > activities.get(0).getLimitmoney()) {
						merchantVO.setActualPrice(total);// 实际总金额
						merchantVO.setTotal(total
								- Double.parseDouble(activities.get(0)
										.getCutmoney().toString()));// 实际支付金额
						merchantVO.setSubPrice(Double.parseDouble(activities
								.get(0).getCutmoney().toString()));// 减免金额
						orderSubPrice += merchantVO.getSubPrice(); // 累计订单减免金额
					} else {
						merchantVO.setActualPrice(total);// 实际总金额
						merchantVO.setTotal(total);// 实际支付金额
						merchantVO.setSubPrice(0.0);// 减免金额
					}
				} else {
					merchantVO.setActualPrice(total);// 实际总金额
					merchantVO.setTotal(total);// 实际支付金额
					merchantVO.setSubPrice(0.0);// 减免金额
				}
				// 商户vo
				merchantVO.setMerchant(merchant);
				merchantVO.setMerchantId(merchant.getId());
				merchantVO.setGoodsList(goodsVOlists);
				merchantVOlists.add(merchantVO);
			}
		}

		// 查询平台活动
//		List<PlatformActivity> bankActivities = platformActivityDao
//				.findByStatusAndType(StatusEnum.NORMAL.getValue(), 0);
//		if (bankActivities.size() > 0) {
//			// 符合平台满减活动
//			if (cart.getTotal() > bankActivities.get(0).getLimitmoney()) {
//				// 累计订单减免金额
//				orderSubPrice += bankActivities.get(0).getCutmoney();
//			}
//		}
		// 购物车总金额
		double temp = cartService.getTotal(cart);
		
		//计算使用优惠券之后的金额
		if (marketId == MarketEnum.BRAND.getValue()) {
			orderSubPrice += getCouponAfterTotal(temp-orderSubPrice,couponRecordId);
		}
		
		OrderVO orderVO = new OrderVO();// 订单vo对象
		orderVO.setTotal(temp - orderSubPrice);// 订单实际支付金额
		orderVO.setActualPrice(temp);// 订单实际金额
		orderVO.setSubPrice(orderSubPrice);// 订单减免金额
		orderVO.setMerchantList(merchantVOlists);// 商户集合
	

		return orderVO;
	}

	// 计算使用优惠券的金额
	@Override
	public double getCouponAfterTotal(double total,Long couponRecordId) {
		if (couponRecordId != null && couponRecordId > 0) {
			// 获取优惠券
			CouponRecord couponRecord = couponRecordDao.findByIdAndAndRuleMinAmountLessThanEqualAndRuleUsageAmountLessThanEqualAndStatusAndRuleStartTimeLessThanEqualAndRuleEndTimeGreaterThanEqual(couponRecordId, total, total, CouponRecordStatusEnum.UNUSED.getValue(), new Date(), new Date());
			if (couponRecord != null) {
				couponRecord.setStatus(1);// 状态改为已使用
				couponRecordDao.save(couponRecord);
				return couponRecord.getRule().getUsageAmount();
			}
		}
		return 0.0;
	}
	
	/** 判断库存  false 表示失败*/
	public boolean checkInventory(OrderPlat orderPlat) throws Exception{
		
		if(orderPlat!=null && orderPlat.getOrderList().size()>0){
			//所有商户订单
			List<Order> orderList = orderPlat.getOrderList();
			for (Order order : orderList) {
				
				List<OrderItem> items = orderItemDao.findByOrderId(order.getId());
				for (OrderItem item : items) {
					if(item.getGoods().getIsInventory()==YesOrNoEnum.YES.getValue()){
						 //* false表示失败
						boolean f = goodsService.checkInventory(item.getGoods(), item.getAmount());
						if(!f){
							return false;
						}
					}
				}
			}
		}
		return true;
	}
	
	
	/** wap 任务调度 查询订单未支付方法*/
	@Override
	public boolean quartzOrder( Integer status) {
		try {
			 
			List<OrderPlat> orderPlats=orderPlatDao.findOrderPlat(status,OrderStatusEnum.NOTPAY.getValue());
			Date date=new Date();//当前时间
			boolean isdelete=true;
			//遍历银行订单
			for (int i = 0; i < orderPlats.size(); i++) {
				//时间差
				long interval =(date.getTime()-orderPlats.get(i).getCreateTime().getTime())/1000;//转化minute
				//判断订单15分钟内没有支付的话删除订单,返回库存
				if(interval >= 3600 ){
					//商户订单列表
					List<Order> orderList=orderDao.findByOrderPlatId(orderPlats.get(i).getId());
					
					for (int j = 0; j < orderList.size(); j++) {
						//商户订单列表详情列表
						List<OrderItem> orderItems=orderItemDao.findByOrderId(orderList.get(j).getId());
						for (int k = 0; k < orderItems.size(); k++) {
							//判断商品是否启用库存 启用库存 返回存库数量
							if(orderItems.get(k).getGoods().getIsInventory()==YesOrNoEnum.YES.getValue()){
								orderItems.get(k).getGoods().setRemain(orderItems.get(k).getGoods().getRemain()+orderItems.get(k).getAmount());
								goodsDao.save(orderItems.get(k).getGoods());
								//删除订单明细记录 
								//orderItemDao.delete(orderItems.get(k).getId());
							}
						}
						if(isdelete==true){
							//删除商户订单记录
							orderList.get(j).setStatus(OrderStatusEnum.DEL.getValue());
							orderDao.save(orderList.get(j));
						}
					}
					if(isdelete==true){
						//删除银行订单记录
						orderPlats.get(i).setStatus(OrderStatusEnum.DEL.getValue());
						orderPlatDao.save(orderPlats.get(i));
					}
				}
			}
			return true;
		} catch (Exception e) {
			e.printStackTrace();
			return false;
		}
	}
	

	@Override
	public HSSFWorkbook exportFile(String startTime,String endTime,Integer paystatus) {
		
	    try {
	    	//创建wb
			HSSFWorkbook wb = new HSSFWorkbook();    
	        HSSFSheet sheet = wb.createSheet("Order"); 
		    
		    Row row = sheet.createRow(0);
		    row.createCell(0).setCellValue("银行订单号"); 
		    row.createCell(1).setCellValue("电话");    
		    row.createCell(2).setCellValue("支付金额");    
		    row.createCell(3).setCellValue("时间");    
		    row.createCell(4).setCellValue("收货人");
		    row.createCell(5).setCellValue("收货地址");    
		    row.createCell(6).setCellValue("联系电话");    
		   
		    
		    //step2 遍历openid
		    Collection<SearchFilter> filters = new ArrayList<SearchFilter>();
		    //1 已支付
		    filters.add(new SearchFilter("paystatus", Operator.EQ, paystatus));
		    filters.add(new SearchFilter("createTime", Operator.GE, startTime));
		    filters.add(new SearchFilter("createTime", Operator.LE, endTime));
		    Specification<OrderPlat> spec = DynamicSpecifications.bySearchFilter(filters, OrderPlat.class);
		    List<OrderPlat> dblist=orderPlatDao.findAll(spec);
		    for (int i = 0; i < dblist.size(); i++) {
		    	OrderPlat op = dblist.get(i);
		        row = sheet.createRow(i+1);    
		        row.createCell(0).setCellValue("`"+op.getOrderno()); 
		        row.createCell(1).setCellValue(op.getOrderList().get(0).getMember().getUsername());
		        row.createCell(2).setCellValue(op.getTotal());    
		        row.createCell(3).setCellValue(CommonUtil.formatDate(op.getCreateTime()));    
		        row.createCell(4).setCellValue(op.getOrderList().get(0).getReceiver());  
		        row.createCell(5).setCellValue(op.getOrderList().get(0).getAddress());    
		        row.createCell(6).setCellValue(op.getOrderList().get(0).getTelephone());    
		       
		    }
			wb.close();
			return wb;
		} catch (IOException e) {
			e.printStackTrace();
			return null;
		}
	   
	}
	
	 
}
